package org.glut.wechat.moments.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.glut.wechat.moments.bo.User;
import org.glut.wechat.moments.domain.Moments;
import org.glut.wechat.moments.domain.MomentsLikes;
import org.glut.wechat.moments.domain.MomentsPermission;
import org.glut.wechat.moments.dto.MomentPublishDTO;
import org.glut.wechat.moments.dto.MomentUpdateDTO;
import org.glut.wechat.moments.feign.PersonalCenterFeignService;
import org.glut.wechat.moments.mapper.MomentsCommentMapper;
import org.glut.wechat.moments.mapper.MomentsLikesMapper;
import org.glut.wechat.moments.mapper.MomentsMapper;
import org.glut.wechat.moments.mapper.MomentsPermissionMapper;
import org.glut.wechat.moments.service.MomentsService;
import org.glut.wechat.moments.vo.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatusCode;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

/**
 * 朋友圈服务实现类
 */
@Service
public class MomentsServiceImpl extends ServiceImpl<MomentsMapper, Moments> implements MomentsService {

    @Autowired
    private MomentsPermissionMapper momentsPermissionMapper;
    @Autowired
    private MomentsLikesMapper momentsLikesMapper;
    @Autowired
    private MomentsCommentMapper momentsCommentMapper;

    @Autowired
    private PersonalCenterFeignService personalCenterFeignService;

    @Transactional
    @Override
    public void publishMoments(MomentPublishDTO momentPublishDTO) {
        Moments moments = new Moments();
        BeanUtils.copyProperties(momentPublishDTO, moments);
        moments.setCreateTime(LocalDateTime.now());
        baseMapper.insert(moments);
        if (momentPublishDTO.getPermission() == 2 || momentPublishDTO.getPermission() == 3) {
            momentPublishDTO.getPermissionUserList().forEach(item -> {
                MomentsPermission momentsPermission = new MomentsPermission();
                momentsPermission.setUserId(item);
                momentsPermission.setMomentId(moments.getId());
                momentsPermissionMapper.insert(momentsPermission);
            });
        }
    }

    @Override
    public UserMomentWrapperVO getMomentsByUserId(Page<UserMomentItemVO> page, Integer userId, Integer currentUserId) {
        UserMomentWrapperVO userMomentWrapperVO = new UserMomentWrapperVO();
        ResponseEntity<User> userInfo = personalCenterFeignService.getUserInfo(userId);
        if(userInfo.getBody()==null){
            throw new RuntimeException("用户不存在");
        }
        User body = userInfo.getBody();
        userMomentWrapperVO.setAvatar(body.getAvatar());
        userMomentWrapperVO.setUserId(userId);
        userMomentWrapperVO.setUsername(body.getUsername());
        userMomentWrapperVO.setSignature(body.getSignature());
        if(currentUserId.equals(userId)) {
            userMomentWrapperVO.setMomentItemList(baseMapper.selectOneselfPage(page,currentUserId));
            return userMomentWrapperVO;
        }
        userMomentWrapperVO.setMomentItemList(baseMapper.getMomentsByUserId(page, userId,currentUserId));
        return userMomentWrapperVO;
    }

    @Override
    public MainMomentWrapperVO getPublicMoments(Page<MainMomentItemVO> page, Integer userId) {
        MainMomentWrapperVO mainMomentWrapperVO = new MainMomentWrapperVO();
        ResponseEntity<User> userInfo = personalCenterFeignService.getUserInfo(userId);
        if(userInfo.getBody()==null){
            throw new RuntimeException("用户不存在");
        }
        User body = userInfo.getBody();
        mainMomentWrapperVO.setAvatar(body.getAvatar());
        mainMomentWrapperVO.setUserId(userId);
        mainMomentWrapperVO.setUsername(body.getUsername());
        IPage<MainMomentItemVO> publicMomentItemVOIPage = baseMapper.selectPublicMomentsPage(page, userId);
        publicMomentItemVOIPage.getRecords().forEach(item -> {
            item.setLikeUserList(momentsLikesMapper.selectByMomentId(item.getId()));
            item.setCommentList(momentsCommentMapper.selectByMomentId(item.getId()));
            LikeUserItemVO likeUserItemVO = item.getLikeUserList().stream().filter(likeUser -> likeUser.getUserId().equals(userId)).findFirst().orElse(null);
            if (likeUserItemVO != null) {
                item.setIsLike(1);
            } else {
                item.setIsLike(0);
            }
        });
        mainMomentWrapperVO.setMomentItemList(publicMomentItemVOIPage);
        return mainMomentWrapperVO;
    }

    @Transactional
    @Override
    public void deleteMoments(Integer id) {
        baseMapper.deleteById(id);
        LambdaQueryWrapper<MomentsPermission> momentsPermissionLambdaQueryWrapper = new LambdaQueryWrapper<>();
        momentsPermissionLambdaQueryWrapper.eq(MomentsPermission::getMomentId, id);
        momentsPermissionMapper.delete(momentsPermissionLambdaQueryWrapper);
        LambdaQueryWrapper<MomentsLikes> momentsLikesLambdaQueryWrapper = new LambdaQueryWrapper<>();
        momentsLikesLambdaQueryWrapper.eq(MomentsLikes::getMomentId, id);
        momentsLikesMapper.delete(momentsLikesLambdaQueryWrapper);
    }

    @Override
    public MainMomentItemVO getMomentsById(Integer id, Integer userId) {
        MainMomentItemVO mainMomentItemVO = baseMapper.getMomentsById(id);
        if(mainMomentItemVO == null){
            throw new RuntimeException("朋友圈不存在");
        }
        mainMomentItemVO.setLikeUserList(momentsLikesMapper.selectByMomentId(id));
        mainMomentItemVO.setCommentList(momentsCommentMapper.selectByMomentId(id));
        LikeUserItemVO likeUserItemVO = mainMomentItemVO.getLikeUserList().stream().filter(likeUser -> likeUser.getUserId().equals(userId)).findFirst().orElse(null);
        if (likeUserItemVO != null) {
            mainMomentItemVO.setIsLike(1);
        } else {
            mainMomentItemVO.setIsLike(0);
        }
        ResponseEntity<User> userInfo = personalCenterFeignService.getUserInfo(userId);
        if(userInfo.getBody()==null){
            throw new RuntimeException("用户不存在");
        }
        User body = userInfo.getBody();
        mainMomentItemVO.setCurrentUsername(body.getUsername());
        mainMomentItemVO.setCurrentAvatar(body.getAvatar());
        return mainMomentItemVO;
    }

    @Transactional
    @Override
    public void updateMoments(MomentUpdateDTO momentUpdateDTO) {
        Moments moments = baseMapper.selectById(momentUpdateDTO.getId());
        moments.setType(momentUpdateDTO.getType());
        baseMapper.updateById(moments);
        LambdaQueryWrapper<MomentsPermission> momentsPermissionLambdaQueryWrapper = new LambdaQueryWrapper<>();
        momentsPermissionLambdaQueryWrapper.eq(MomentsPermission::getMomentId, momentUpdateDTO.getId());
        momentsPermissionMapper.delete(momentsPermissionLambdaQueryWrapper);
        if (momentUpdateDTO.getType() == 2 || momentUpdateDTO.getType() == 3) {
            momentUpdateDTO.getPermissionUserList().forEach(item -> {
                MomentsPermission momentsPermission = new MomentsPermission();
                momentsPermission.setUserId(item);
                momentsPermission.setMomentId(moments.getId());
                momentsPermissionMapper.insert(momentsPermission);
            });
        }
    }
}
